//
//  HMComposeView.swift
//  微博
//
//  Created by 程双岐 on 16/9/27.
//  Copyright © 2016年 heima. All rights reserved.
//

import UIKit
import pop

class HMComposeView: UIView {
    
    var target: UIViewController?

    private lazy var  loganImageView: UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    
    private lazy var buttonArray: [HMComponseButton] = [HMComponseButton]()
    private lazy var composeMenuArray: [HMComposeMenu] = self.loadComposePlistData()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.size = CGSize(width: ScrenWidth, height: ScrenHeight)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        let image = UIImage.screenShot().applyLightEffect()
        let bgImage = UIImageView(image: image)
        addSubview(bgImage)
        addSubview(loganImageView)
        
        loganImageView.snp_makeConstraints { (make) in
            make.top.equalTo(self).offset(100)
            make.centerX.equalTo(self)
        }
        

        addChildButton()
        
        
    }
    
    private func startPopAnimation(isUp : Bool){
        
        if isUp == false {
            buttonArray = buttonArray.reversed()
        }
        
        for (i,button) in buttonArray.enumerated(){
            
            let popAnimation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            

            if isUp {
                popAnimation?.toValue = NSValue(cgPoint: CGPoint(x: button.centerX, y: button.centerY - 350))

            }else{
                popAnimation?.toValue = NSValue(cgPoint: CGPoint(x: button.centerX, y: button.centerY + 350))

            }
            
            popAnimation?.springSpeed = 10
            
            popAnimation?.springBounciness = 10
            
            popAnimation?.beginTime = CACurrentMediaTime() + Double(i) * 0.025
            
            button.pop_add(popAnimation, forKey: nil)
        }
        
    }
    
    private func addChildButton(){
        let buttonWidth: CGFloat = 80
        
        let buttonHeight: CGFloat = 110
        
        let buttonMargin: CGFloat = (width - 3 * buttonWidth) / 4
        
        
        for i in 0..<composeMenuArray.count{
            
            let colIndex = i % 3
            let rowIndex = i / 3
            let composeMenu = composeMenuArray[i]
            let button = HMComponseButton()
            button.addTarget(self, action: #selector(buttonACtion(btn:)), for: .touchUpInside)
            
            button.x = CGFloat(colIndex) * buttonWidth + CGFloat(colIndex + 1) * buttonMargin
            button.y = CGFloat(rowIndex) * buttonHeight + CGFloat(rowIndex) * buttonMargin + ScrenHeight
            button.size = CGSize(width: buttonWidth, height: buttonHeight)
            button.setImage(UIImage(named:composeMenu.icon!), for: .normal)
            button.setTitle(composeMenu.title!, for: .normal)
            button.tag = i
            addSubview(button)
            buttonArray.append(button)
        }
    }
    
//    private func screenShot() -> UIImage{
//        
//        let window = UIApplication.shared.keyWindow!
//        //开启上下文
//        UIGraphicsBeginImageContext(window.size)
//        
//        // false表示我不需要等待更新后去绘制图片
//        window.drawHierarchy(in: window.bounds, afterScreenUpdates: false)
//        
//        //从图片上下文中获取图片
//        let image = UIGraphicsGetImageFromCurrentImageContext()
//        
//        
//        UIGraphicsEndPDFContext()
//        
//        return image!
//    }
    
     @objc private func buttonACtion(btn: UIButton){

        
        UIView.animate(withDuration: 0.25, animations: {
            for button in self.buttonArray{
                button.alpha = 0.7
                if button == btn{
                    button.transform = CGAffineTransform(scaleX: 2, y: 2)
                }else{
                    button.transform = CGAffineTransform(scaleX: 0.2, y: 0.2)
                    
                }
                
            }

            
            }) { (_) in
                UIView.animate(withDuration: 0.25, animations: { 
                    for button in self.buttonArray{
                        button.transform = CGAffineTransform.identity
                        button.alpha = 1
                    }
                    }, completion: { (_) in
                        
//                        let name = "HMComposeViewControllew"
//                        let classType = NSClassFromString(name)! as! UIViewController.Type
//                        
//                          let vc = classType.init()
                        //  获取指定模型
                        let composeMenu = self.composeMenuArray[btn.tag]
                        //  获取对应的class
                        let classType = NSClassFromString(composeMenu.className!)! as! UIViewController.Type
                        //  根据class创建对象
                        let vc = classType.init()
                        //  vc放到导航控制器里面
                        let nav = HMNavigationViewController(rootViewController: vc)
                        self.target?.present(nav, animated: true, completion: {
                            //  移除罩层
                            self.removeFromSuperview()
                        })
                        
                })
        }
    }
    
    func show(target: UIViewController) {
        self.target = target
//        let window = UIApplication.shared.windows.last!
//        window.addSubview(self)
        target.view.addSubview(self)
        startPopAnimation(isUp: true)

    }
    
    private func loadComposePlistData() -> [HMComposeMenu] {
        let path = Bundle.main.path(forResource: "compose.plist", ofType: nil)!
        let dicArray = NSArray(contentsOfFile: path)!
        
        let modelArray = NSArray.yy_modelArray(with: HMComposeMenu.self, json: dicArray)! as! [HMComposeMenu]
        
        return modelArray
        
        
        
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        startPopAnimation(isUp: false)
//        removeFromSuperview()
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) { 
            self.removeFromSuperview()
        }
    }
    
    
    
}
